package com.focus.xyz.core.utils;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.util.concurrent.TimeUnit;

/**
 * Created by chenmeng on 2016/4/6.
 */
public class ElementUtils {
    private final static long WAIT_TIME = 10000L;

    public static void selectCheckBox(WebElement webElement) throws Exception {
        if (!webElement.isSelected()) {
            webElement.click();
        }
    }

    public static void deselectCheckBox(WebElement webElement) throws Exception {
        if (webElement.isSelected()) {
            webElement.click();
        }
    }

    public static void inputText(WebElement input, String text) throws Exception {
        input.clear();
        input.sendKeys(text);
    }


    public void pause(long time, TimeUnit unit) {
        try {
            Thread.sleep(unit.toMillis(time));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void pause(long millis) {
        pause(millis, TimeUnit.MILLISECONDS);
    }

    public static void click(WebDriver driver, WebElement element) {
        click(driver,element,0);
    }

    public static void click(WebDriver driver, WebElement element,long waitTime) {
        WebDriverWait wait = null;
        if(waitTime == 0){
            wait = new WebDriverWait(driver, TimeUnit.MILLISECONDS.toSeconds(WAIT_TIME));
        }else{
            wait = new WebDriverWait(driver, TimeUnit.MILLISECONDS.toSeconds(waitTime));
        }
        WebElement webElement = wait.until(ExpectedConditions.elementToBeClickable(element));
        webElement.click();
    }

    public static void doubleClick(WebDriver driver,WebElement element){
        doubleClick(driver,element,0);
    }

    public static void doubleClick(WebDriver driver,WebElement element,long waitTime){
        WebDriverWait wait = null;
        if(waitTime == 0){
            wait = new WebDriverWait(driver, TimeUnit.MILLISECONDS.toSeconds(WAIT_TIME));
        }else{
            wait = new WebDriverWait(driver, TimeUnit.MILLISECONDS.toSeconds(waitTime));
        }
        WebElement webElement = wait.until(ExpectedConditions.elementToBeClickable(element));
        Actions actions = new Actions(driver);
        actions.doubleClick(webElement);
    }



}
